#!/usr/bin/env python3
"""
Script to compile the README.ipynb notebook to markdown and process image paths.

This script converts the Jupyter notebook README.ipynb to a markdown file,
and updates image paths to point to the GitHub repository.
"""

import os
import shutil

import typer


def post_process(markdown_file: str, original_folder: str, new_folder: str) -> None:
    """
    Process the generated markdown file by moving images and updating paths.

    This function moves image files from the original folder to a new location
    and updates the references in the markdown file to point to the GitHub repository.

    Args:
        markdown_file: Path to the markdown file to process
        original_folder: Original folder containing images generated by nbconvert
        new_folder: New folder where images should be moved

    """
    rel_path = (
        "https://raw.githubusercontent.com/livingbio/typed-ffmpeg/main/" + new_folder
    )

    # Move the folder
    if os.path.exists(original_folder):
        for filepath in os.listdir(original_folder):
            # Move the file, replace if it already exists
            old_path = os.path.join(original_folder, filepath)
            new_path = os.path.join(new_folder, filepath)
            if os.path.exists(new_path):
                os.remove(new_path)

            shutil.move(old_path, new_path)
            print(f"Moved {filepath} to {new_folder}")

    # Update paths in the Markdown file
    with open(markdown_file) as file:
        content = file.read()

    content = content.replace(original_folder, rel_path)

    with open(markdown_file, "w") as file:
        file.write(content)

    print("Image paths updated and folder moved.")


def main() -> None:
    """
    Main function to compile the README notebook and process the output.

    This function removes any existing README.md file, converts the README.ipynb
    notebook to markdown format, and processes the generated markdown file.
    """
    os.remove("README.md")
    os.system("jupyter nbconvert --to markdown README.ipynb")
    assert os.path.exists("README.md")

    post_process("README.md", "README_files", "docs/media/README_files")


if __name__ == "__main__":
    typer.run(main)
